package com.rose.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.rose.common.utils.R;
import com.rose.mall.product.entity.SkuImagesEntity;
import com.rose.mall.product.entity.SpuInfoDescEntity;
import com.rose.mall.product.feign.SeckillFeignService;
import com.rose.mall.product.service.*;
import com.rose.mall.product.vo.*;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rose.common.utils.PageUtils;
import com.rose.common.utils.Query;

import com.rose.mall.product.dao.SkuInfoDao;
import com.rose.mall.product.entity.SkuInfoEntity;
import org.springframework.util.StreamUtils;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService imagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty((String)params.get("key"))){
            wrapper.and((w)->{
                w.eq("id",params.get("key")).or().like("spu_name",params.get("key"));
            });
        }
        // and 相当于是给了一个相关的小括号类似的机制
        // status = 1 and (id = 1 or spu_name like xxx)
        if (!StringUtils.isEmpty((String)params.get("status"))){

            wrapper.eq("publish_status",(String)params.get("status"));
        }
        if (!StringUtils.isEmpty((String)params.get("brandId"))){

            wrapper.eq("brand_id",(String)params.get("brandId"));
        }

        if (!StringUtils.isEmpty((String)params.get("catalogId"))){
            wrapper.eq("catalog_id",(String)params.get("catalogId"));
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    public SkuItemVo item2(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();
        // 1.sku基本信息获取 pms_sku_info
        SkuInfoEntity info = getById(skuId);
        Long catalogId = info.getCatalogId();
        Long spuId = info.getSpuId();

        skuItemVo.setInfo(info);

        // 2.sku的图片信息 pms_sku_images
        List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
        skuItemVo.setImages(images);


        // 3. 获取spu的销售属性组合
        List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
        skuItemVo.setSaleAttr(skuItemSaleAttrVos);


        // 4.获取spu的介绍 pms_spu_info_desc

        SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(spuId);
        skuItemVo.setDesc(spuInfoDescEntity);

        // 5.获取spu的规格参数信息  todo 这个方法未完成
//        List<SkuItemVo.SpuItemBaseAttrVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(spuId,catalogId);
//        skuItemVo.setGroupAttrs(attrGroupVos);


        return skuItemVo;
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        List<SkuInfoEntity> list = this.list(wrapper.eq("spu_id",spuId));
        return list;
    }

    @Override
    public SkuItemVo item3(Long skuId) {
        R skuSeckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
        if (skuSeckillInfo.getCode() == 0) {
            SeckillInfoVo seckillInfoVo = skuSeckillInfo.getData(new TypeReference<SeckillInfoVo>() {});
            System.out.println(seckillInfoVo.toString());
        }
        return null;
    }

    /**
     * 自定义线程串池
     */
    @Autowired
    private ThreadPoolExecutor executor;

//    @Override
//    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
//        SkuItemVo skuItemVo = new SkuItemVo();
//
//        CompletableFuture<SkuInfoEntity> infoFutrue = CompletableFuture.supplyAsync(() -> {
//            //1 sku基本信息
//            SkuInfoEntity info = getById(skuId);
//            skuItemVo.setInfo(info);
//            return info;
//        }, executor);
//
//        CompletableFuture<Void> ImgageFuture = CompletableFuture.runAsync(() -> {
//            //2 sku图片信息
//            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
//            skuItemVo.setImages(images);
//        }, executor);
//
//        CompletableFuture<Void> saleAttrFuture =infoFutrue.thenAcceptAsync(res -> {
//            //3 获取spu销售属性组合
//            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
//            skuItemVo.setSaleAttr(saleAttrVos);
//        },executor);
//
//        CompletableFuture<Void> descFuture = infoFutrue.thenAcceptAsync(res -> {
//            //4 获取spu介绍
//            SpuInfoDescEntity spuInfo = spuInfoDescService.getById(res.getSpuId());
//            skuItemVo.setDesc(spuInfo);
//        },executor);
//
//        CompletableFuture<Void> baseAttrFuture = infoFutrue.thenAcceptAsync(res -> {
//            //5 获取spu规格参数信息
//            List<SkuItemVo.SpuItemBaseAttrVo> attrGroups = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
//            skuItemVo.setGroupAttrs(attrGroups);
//        }, executor);
//
//        // 6.查询当前sku是否参与秒杀优惠
//        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
//            R skuSeckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
//            if (skuSeckillInfo.getCode() == 0) {
//                SeckillInfoVo seckillInfoVo = skuSeckillInfo.getData(new TypeReference<SeckillInfoVo>() {});
//                System.out.println("SkuInfoServiceImpl===>"+seckillInfoVo.toString());
//                skuItemVo.setSeckillInfoVo(seckillInfoVo);
//            }
//        }, executor);
//
//
//        // 等待所有任务都完成再返回
//        CompletableFuture.allOf(ImgageFuture,saleAttrFuture,descFuture,baseAttrFuture,secKillFuture).get();
//        return skuItemVo;
//    }

    /**
     * 查询页面详细内容
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        log.info("复制来的");
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFutrue = CompletableFuture.supplyAsync(() -> {
            //1 sku基本信息
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);

        CompletableFuture<Void> ImgageFuture = CompletableFuture.runAsync(() -> {
            //2 sku图片信息
            List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);

        CompletableFuture<Void> saleAttrFuture =infoFutrue.thenAcceptAsync(res -> {
            //3 获取spu销售属性组合 getSaleAttrsBySpuId
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        },executor);


        CompletableFuture<Void> descFuture = infoFutrue.thenAcceptAsync(res -> {
            //4 获取spu介绍
            SpuInfoDescEntity spuInfo = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfo);
        },executor);

        CompletableFuture<Void> baseAttrFuture = infoFutrue.thenAcceptAsync(res -> {
            //5 获取spu规格参数信息
            List<SkuItemVo.SpuItemBaseAttrVo> attrGroups = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroups);
        }, executor);

        // 6.查询当前sku是否参与秒杀优惠
        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
            log.info("是否走进==>secKillFuture");

            R skuSeckillInfo = seckillFeignService.getSkuSeckillInfo(skuId);
            if (skuSeckillInfo.getCode() == 0) {
                SeckillInfoVo seckillInfoVo = skuSeckillInfo.getData(new TypeReference<SeckillInfoVo>() {});
                skuItemVo.setSeckillInfoVo(seckillInfoVo);
            }
        }, executor);


        // 等待所有任务都完成再返回
        CompletableFuture.allOf(ImgageFuture,saleAttrFuture,descFuture,baseAttrFuture,secKillFuture).get();

        return skuItemVo;
    }


}